var tree, treemenu = $("#treemenu");
var resourceTree;
var userTable = $("#userTable");
/**
 * ztree 属性设置
 */
var setting = {
	async : {
		enable : true,
		type:"get", 
		url : "/auth/role/"
	},
	callback : {
		onRightClick : rightClick,
		onClick : onnodeclick
	},
	data : {
		simpleData : {
			enable : true,
			idKey : "id",
			pIdKey : "pid"
		}
	},
	view : {
		fontCss : function(treeId, treeNode) {
			return (!treeNode.highlight) ? {
				color : "#696969",
				"font-weight" : "normal"
			} : {
				color : "#800000",
				"font-weight" : "bold"
			};
		}
	}
};

var options = {
	data : {
		simpleData : {
			enable : true,
			idKey : "id",
			pIdKey : "pid"
		}
	},
	check : {
		enable : true
	},
	async : {
		enable : true,
		type:"get", 
		url : "/auth/roleResource/"
	}
};

$(function() {
	/**
	 * 初始化ztree
	 */
	tree = $.fn.zTree.init($("#roleTree"), setting);
	resourceTree = $.fn.zTree.init($("#resourceTree"), options);
	initTable();
});

function initTable(){
	userTable.bootstrapTable({
		queryParams: function (params) {
        	var query = {  
        		limit: params.limit,
    	        offset: params.offset,
    	        sortName:this.sortName,
                sortOrder:this.sortOrder
            } 
        	return query;
        },
	});
}

/**
 * 节点右键点击事件
 * 
 * @param event
 * @param treeId
 * @param treeNode
 * @returns
 */
function rightClick(event, treeId, treeNode) {
	console.info(treeNode);
	tree.selectNode(treeNode);// 选中当前节点
	showRMenu(treeNode, event.clientX, event.clientY);
}

/**
 * 显示右键菜单
 * @param treeNode
 * @param x
 * @param y
 * @returns
 */
function showRMenu(treeNode, x, y) {
	var pid = treeNode.pid;
	treemenu.show();
	treemenu.css({
		"top" : (y - 100) + "px",
		"left" : (x + 34) + "px",
		"visibility" : "visible"
	});
	if (pid == '' || pid == null) {
		$("#tree_add").show();
		$("#tree_remove").hide();
		$("#tree_edit").hide();
	} else {
		$("#tree_add").hide();
		$("#tree_remove").show();
		$("#tree_edit").show();
	}
	$("body").bind("mousedown", onBodyMouseDown);
}

/**
 * 隐藏右键菜单
 * @returns
 */
function hideRMenu() {
	if (treemenu)
		treemenu.css({
			"visibility" : "hidden"
		});
	$("body").unbind("mousedown", onBodyMouseDown);
}

function onBodyMouseDown(event) {
	if (!(event.target.id == "treemenu" || $(event.target).parents("#treemenu").length > 0)) {
		treemenu.css({
			"visibility" : "hidden"
		});
	}
}

/**
 * 节点树选中单击事件
 * @param event
 * @param treeId
 * @param treeNode
 * @param clickFlag
 * @returns
 */
function onnodeclick(event, treeId, treeNode, clickFlag) {

	var treeNodes = tree.transformToArray(tree.getNodes());
	for (var i = 0; i < treeNodes.length; i++) {
		treeNodes[i].highlight = false;
		tree.updateNode(treeNodes[i]);
	}

	// 判断是否为最后一级节点，即显示角色的节点
	var isParent = treeNode.isParent;
	if (!isParent) {
		// 获取节点ID 刷新角色用户列表
		var roleRowKey = treeNode.obj.roleRowKey;
		userTable.bootstrapTable("refresh", {
			url : "/auth/role/getRoleUserList?roleRowKey=" + roleRowKey
		});
		// 更新资源树的状态
		// 获取角色树的id
		var roleRefid = "";
		var selectTreeNode = tree.getSelectedNodes()[0];
		if (selectTreeNode) {
			roleRefid = selectTreeNode.id;
			selectTreeNode.highlight = true;
			tree.updateNode(selectTreeNode);// 执行修改
		}
		$.ajax({
			url : "/auth/roleResource/"+ roleRefid,
			type:"PUT",
			headers: { 
			      "Content-Type": "application/json",
			      "X-HTTP-Method-Override": "PUT" 
			}, //PUT,DELETE
			dataType : "json",
			async : false,
			success : function(result) {
				if (result.status === "OK") {
					var resourceTreeObj = $.fn.zTree
							.getZTreeObj("resourceTree");
					resourceTreeObj.checkAllNodes(false);
					var list = JSON.parse(result.message);
					for (var j = 0; j < list.length; j++) {
						var tem = {};
						tem.id = list[j].resourceRefid;
						var node = resourceTreeObj.getNodeByParam("id", tem.id,
								null);
						node.checked = true;
						resourceTreeObj.updateNode(node);
					}
				} else {
					alertMessage("获取子节点资源失败!");
				}
			}
		});
	}
}

/**
 *  添加节点
 * @returns
 */
function addTreeNode() {
	var platformRefid = "";
	var selectTreeNode = tree.getSelectedNodes()[0];
	if (selectTreeNode) {
		platformRefid = selectTreeNode.id;
	}
	var URL = "/auth/role/editRoleInfo?platformRefid=" + platformRefid;
	$("#roleModal .modal-dialog").load(URL);
	$("#roleModal").modal('show');
}

/**
 * 保存角色节点信息
 * @returns
 */
function saveRoleInfo() {
	$.ajax({
		url : "/auth/role/saveRoleInfo",
		type : "post",
		dataType : "json",
		data : $("#roleForm").serialize(),
		beforeSend : function() {
		},
		success : function(result) {
			if (result.rspCode === "000000") {
				$('#roleModal').modal('hide')
				tree.reAsyncChildNodes(null, "refresh");
			}
			writeLog(result.rspMsg);
		}
	});
}

/**
 * 删除角色节点信息
 * @returns
 */
function removeTreeNode() {
	var refid = "";
	var selectTreeNode = tree.getSelectedNodes()[0];
	if (selectTreeNode) {
		refid = selectTreeNode.id;
	}
	$.ajax({
		url : "/auth/role/"+refid,
		type:"DELETE",
		headers: { 
		      "Content-Type": "application/json",
		      "X-HTTP-Method-Override": "DELETE" 
		}, //PUT,DELETE
		data:{token:refid},
		dataType : "json",
		success : function(result) {
			if (result.rspCode === "000000") {
				tree.reAsyncChildNodes(null, "refresh");
			}
		}
	});
}
/**
 * 编辑角色节点信息
 * @returns
 */
function editTreeNode() {
	var platformRefid = "", refid = "";
	var selectTreeNode = tree.getSelectedNodes()[0];
	if (selectTreeNode) {
		platformRefid = selectTreeNode.pid;
		refid = selectTreeNode.id;
	}
	var URL = "/auth/role/editRoleInfo?platformRefid=" + platformRefid
			+ "&refid=" + refid;
	$("#roleModal .modal-dialog").load(URL);
	$("#roleModal").modal('show');
}

/**
 * 保存资源节点信息
 * @returns
 */
function saveRoleResourceInfo() {
	var roleRefid = "";
	var sourceRefids = [];
	var roleTreeObj = $.fn.zTree.getZTreeObj("roleTree");
	var selectTreeNode = roleTreeObj.getSelectedNodes()[0];
	if (selectTreeNode) {
		roleRefid = selectTreeNode.id;
	}
	var CheckedNodes = resourceTree.getCheckedNodes(true);
	for (var i=0;i<CheckedNodes.length;i++) {
		sourceRefids.push(CheckedNodes[i].id);
	}
	
	var URL = "/auth/roleResource/";
	$.ajax({
		url : URL,
		type : "POST",
		dataType : "json",
		data : {"roleRefid":roleRefid,"resoureRefid":sourceRefids.join(",")},
		success : function(result) {
			writeLog(result.rspMsg);
		}
	});
}

function addUserRole(){
	var platformRefid = "", refid = "";
	var selectTreeNode = tree.getSelectedNodes()[0];
	if (selectTreeNode == null) {
		alertMessage( "角色没选");
		return;
	}
	var roleRowKey = selectTreeNode.obj.roleRowKey;
	if (selectTreeNode) {
		platformRefid = selectTreeNode.pid;
		refid = selectTreeNode.id;
	}
	var URL = "/auth/role/addUserRoleInfoView?platformRefid="
			+ platformRefid + "&refid=" + refid;
	
	$("#userModal .modal-dialog").load(URL);
	$("#userModal").modal('show');
}
